/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package java_project;

import JavaSource.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Xilan Ding
 */
public class OrderStatusGUI extends javax.swing.JFrame {

    /**
     * Creates new form OrderStatusGUI
     */
    public OrderStatusGUI() {
        initComponents();
        this.setLocationRelativeTo(null);
        InitialComboBox();
    }

    /**
     * l
     *
     * @param fos
     * @param pol
     * @param co
     * @param ol
     */
    public OrderStatusGUI(CookGUI cookgui, FoodOrderingSystem fos, LinkedList<Order> pol, Order co) {
        this();
        this.fos = fos;
        this.pol = pol;
        this.currentOrder = co;
        this.refreshOrder();
        this.cookgui = cookgui;
    }

    public void refreshOrder() {
        if(currentOrder!=null){
        OrderNoText1.setText("" + currentOrder.getOrderID());
        OrderStatusText2.setText(currentOrder.getOrderStatus());
        viewOrderStatus(currentOrder);}
        else {
            OrderNoText1.setText("" );
            OrderStatusText2.setText("");
          clearTable(jTable2);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        Title1 = new javax.swing.JLabel();
        OrderNoLabel1 = new javax.swing.JLabel();
        OrderNoText1 = new javax.swing.JTextField();
        OrderStaLabel1 = new javax.swing.JLabel();
        OrderStatusText2 = new javax.swing.JTextField();
        OrderDishListLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setType(java.awt.Window.Type.POPUP);

        Title1.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        Title1.setText("Current Order Status");

        OrderNoLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        OrderNoLabel1.setText("Order Number:");

        OrderNoText1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OrderNoText1ActionPerformed(evt);
            }
        });

        OrderStaLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        OrderStaLabel1.setText("Order Status:");

        OrderStatusText2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OrderStatusText2ActionPerformed(evt);
            }
        });

        OrderDishListLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        OrderDishListLabel1.setText("Dish List:");

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Dish No.", "Dish Name", "Quat.", "Status", "Avalibility"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.setColumnSelectionAllowed(true);
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        if (jTable2.getColumnModel().getColumnCount() > 0) {
            jTable2.getColumnModel().getColumn(0).setResizable(false);
            jTable2.getColumnModel().getColumn(1).setResizable(false);
            jTable2.getColumnModel().getColumn(2).setResizable(false);
            jTable2.getColumnModel().getColumn(3).setResizable(false);
            jTable2.getColumnModel().getColumn(4).setResizable(false);
        }

        jButton1.setText("Update Availability");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Confirm done");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(OrderNoLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(OrderNoText1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(OrderDishListLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(OrderStaLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(OrderStatusText2, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addGap(36, 36, 36))))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(271, 271, 271)
                        .addComponent(Title1))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 692, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(48, 48, 48))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(Title1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OrderNoLabel1)
                    .addComponent(OrderNoText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OrderStaLabel1)
                    .addComponent(OrderStatusText2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(OrderDishListLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(43, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 755, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGap(33, 33, 33)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 640, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(158, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void OrderNoText1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderNoText1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_OrderNoText1ActionPerformed

    private void OrderStatusText2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderStatusText2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_OrderStatusText2ActionPerformed

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked

    }//GEN-LAST:event_jTable2MouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        updateDishAvailability();
        this.refreshOrder();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        checkOrderStatus();

    }//GEN-LAST:event_jButton2ActionPerformed

    private void InitialComboBox() {
        dishStatus = jTable2.getColumnModel().getColumn(3);
        JComboBox comboBox1 = new JComboBox();
        comboBox1.addItem("Pending");
        comboBox1.addItem("Done");
        dishStatus.setCellEditor(new DefaultCellEditor(comboBox1));

        dishAvalibility = jTable2.getColumnModel().getColumn(4);
        JComboBox comboBox2 = new JComboBox();
        comboBox2.addItem("Avalible");
        comboBox2.addItem("Unavalible");
        dishAvalibility.setCellEditor(new DefaultCellEditor(comboBox2));
    }

    private void viewOrderStatus(Order ord) {
        clearTable(jTable2);
        if (ord != null) {
            dishList = ord.getOrderDishes();
            DefaultTableModel m = (DefaultTableModel) (jTable2.getModel());
            m.setRowCount(0);
            for (int i = 0; i < dishList.size(); i++) {
                Dish ds = (Dish) dishList.get(i);
                Object ob[] = {ds.getMenuDish().getDishId(),
                    ds.getMenuDish().getName(), ds.getQty(),
                    ds.getDishStatus(), ds.getMenuDish().isAvailability()};
                m.addRow(ob);
            }
        }
    }

    public Order getNextOrder(Order currentOrder) {
        Iterator<Order> itr = pol.iterator();
        while (itr.hasNext()) {
            Order ord = itr.next();
            if (ord.equals(currentOrder)) {
                if (itr.hasNext()) {
                    return itr.next();
                }
            }
        }
        pol.remove(currentOrder);
        return null;
    }

    public void updateDishAvailability() {
        int i;
        for (i = 0; i < dishList.size(); i++) {
            String a = jTable2.getValueAt(i, 4).toString();
            dishList.get(i).getMenuDish().setAvailability(a);
        }
    }

    public void checkOrderStatus() {
        // Check if all the dishes in the order has been done,if all the status 
        // are "Done",make the order status into "Ready for delivery/Pick-up"
        // and give the next order view.
        int i, count = 0;
        int t = -1;
        for (i = 0; i < dishList.size(); i++) {
            String s = jTable2.getValueAt(i, 3).toString();
            dishList.get(i).setDishStatus(s);
            Dish d = dishList.get(i);
            if (d.getDishStatus().equals("Done")) {
                count++;
            }
        }
        if (count == dishList.size()) {
            t = currentOrder.getOrderType();
            if (t == 0) {
                currentOrder.setOrderStatus("Ready for Delivery");
                JOptionPane.showMessageDialog(null, "Ready for Delivery");
            } else if (t == 1) {
                currentOrder.setOrderStatus("Ready for Pick-up");
                JOptionPane.showMessageDialog(null, "Ready for Pick-up");
            } else {
                JOptionPane.showMessageDialog(null, "O0000Ps!");
            }
            
            this.cookgui.refreshList();  
            currentOrder = getNextOrder(currentOrder);
            if(currentOrder!=null){
                viewOrderStatus(currentOrder);
                refreshOrder();
            } else {
                 refreshOrder();
            }
        }
    }

    public void clearTable(JTable table) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        for (int index = model.getRowCount() - 1; index >= 0; index--) {
            model.removeRow(index);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OrderStatusGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OrderStatusGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OrderStatusGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OrderStatusGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OrderStatusGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel OrderDishListLabel1;
    private javax.swing.JLabel OrderNoLabel1;
    private javax.swing.JTextField OrderNoText1;
    private javax.swing.JLabel OrderStaLabel1;
    private javax.swing.JTextField OrderStatusText2;
    private javax.swing.JLabel Title1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables
    private FoodOrderingSystem fos;
    private LinkedList<Order> pol;
    private Order currentOrder;
    private javax.swing.table.TableColumn dishStatus;
    private javax.swing.table.TableColumn dishAvalibility;
    private LinkedList<Dish> dishList;
    CookGUI cookgui;

}
